#region using Statements

using System;
using System.Data;
using System.Configuration;
using System.Collections.Specialized;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Windows.Live.SSO;

#endregion

public partial class _Redirect : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        NameValueCollection appSettings = ConfigurationManager.AppSettings;

        if (String.IsNullOrEmpty(Page.User.Identity.Name))
        {
            lblError.Text = HttpUtility.HtmlEncode("Cannot identify the user.  Make sure anonymous access is not turned on in the IIS application.");
            return;
        }

        string wlUserID = WLID.GetWindowsLiveID(Page.User.Identity.Name, appSettings["scenario"]);

        if ((!wlUserID.Contains("@")) || (wlUserID.IndexOf("@") == 0))
        {
            lblError.Text = HttpUtility.HtmlEncode("The Windows Live ID for the user is invalid or the user cannot be found.");
            return;
        }

        LiveSLT ticket = new LiveSLT(appSettings["certThumb"],
                                     appSettings["siteID"],
                                     appSettings["webProxy"],
                                     int.Parse(appSettings["loginSeconds"]));
        string slt = ticket.GetSLT(wlUserID, appSettings["siteID"]);

        if ((String.IsNullOrEmpty(slt)) || (!ticket.Success))
        {
            lblError.Text = HttpUtility.HtmlEncode(ticket.CustomExceptionMessage);
            return;
        }

        string redirectUrl = Request["RedirectURL"];
        if (String.IsNullOrEmpty(redirectUrl))
        {
            try
            {
                redirectUrl = appSettings["redirectURL"];
            }
            catch { }
        }
        if (String.IsNullOrEmpty(redirectUrl))
        {
            lblError.Text = HttpUtility.HtmlEncode("RedirectURL is a required appSetting in the web.config.");
            return;
        }
        redirectUrl = Server.UrlDecode(redirectUrl);

        string sltUrl = LiveRPS.CreateRedirectString(slt, redirectUrl, appSettings["siteID"]);

        if (Request.Browser.EcmaScriptVersion.Major > 0)
        {
            sltUrl = sltUrl.Substring(0, sltUrl.IndexOf("&slt"));
            string sltScript = String.Format("postSlt('{0}','{1}');", sltUrl, slt);
            ClientScript.RegisterStartupScript(typeof(Page), "SLT", sltScript, true);
        }
        else
        {
            Response.Redirect(sltUrl);
            Response.End();
        }
    }
}
